package controllers

import (
	. "AndroidBlog/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Post() {
	c.Get()
}

func (c *UserController) Get() {
	method := c.Ctx.Input.Param(":path")
	if "register" == method {
		u := c.GetString("username", "-")
		p := c.GetString("password", "-")
		fmt.Println("u:", u, "pwd:", p)
		re := register(u, p)
		c.Ctx.WriteString("hello,android blog,注册" + re)
	} else if "login" == method {
		u := c.GetString("username", "-")
		p := c.GetString("password", "-")
		fmt.Println("u:", u, "pwd:", p)
		re := login(u, p)
		c.Ctx.WriteString("hello,android blog,登陆： " + re)
	} else {
		c.Ctx.WriteString("hello,android blog,404")
	}
}

/**
 注册返回返回值
 */
func register(u string, p string) (result string) {
	user, code := UserRegister(u, p)
	if code == SQL_SUCCESS {
		fmt.Println("d")
		bytes, e := json.Marshal(user)
		if e == nil {
			return string(bytes)
		}
		return "注册成功--异常 "
	} else if code == SQL_UNKNOW {
		fmt.Println(user)
		return "异常"
	} else if code == SQL_EXSIT {
		bytes, e := json.Marshal(user)
		fmt.Println(string(bytes), "- ", e)
		return "用户名已存在"
	}
	return "---"
}

/**
 登录返回返回值
 */
func login(u string, p string) (result string) {
	user, code := UserLogin(u, p)
	if code == SQL_SUCCESS {
		bytes, e := json.Marshal(user)
		if e == nil {
			return string(bytes)
		}
		return "登陆数据异常 "
	}
	return "用户名或密码不对"
}
